import { Component } from 'react';
import { globalStore } from '@/store';
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { observer } from 'mobx-react';
import { getShopList } from '@/service/apis/shop';
import ShopItem from './components/ShopItem/index';
import './list-vip.scss';

class Index extends Component {
  state = {
    shopList: [],
    type: 'edit',
  };

  componentDidMount() {
    globalStore.getLocation(true).then((res) => {
      this.getShopList(res);
    });
  }

  getShopList = async (pos?: any) => {
    const { lat = 0, lng = 0 } = pos || {};
    try {
      const { data } = await getShopList({
        lat,
        lng,
      });
      console.log('data', data);
      this.setState({
        shopList: data.store_list,
      });
    } catch (err) {
      Taro.showToast({
        icon: 'none',
        title: err?.msg,
      });
    }
  };

  onShopChange = async (shop) => {
    if (this.state.type === 'view') {
      return false;
    }
    Taro.showToast({
      title: '切换成功',
    });
    globalStore.updateVipShop(shop);
    setTimeout(() => {
      Taro.navigateBack({});
    }, 2000);
  };

  getLocation = async () => {
    globalStore.getLocation(true).then((res) => {
      this.getShopList(res);
    });
  };

  render() {
    const { type, shopList } = this.state;
    return (
      <View className="shop-container">
        <View className="shop-top">
          <View className="shop-container-title">
            所有门店<Text>({shopList?.length}家）</Text>
          </View>
          {type === 'edit' && (
            <View className="location" onClick={this.getLocation}>
              重新定位
            </View>
          )}
        </View>
        {shopList.map((item) => {
          return (
            <ShopItem
              isSelected={globalStore?.currentVipShop.id === item.id}
              key={item.id}
              shop={item}
              onChange={this.onShopChange}
              type={type}
            />
          );
        })}
      </View>
    );
  }
}

export default observer(Index);
